<template>
  <div class="formBox">
    <div v-if="formObject.displayType===1">
      <el-tabs type="border-card" v-model="tabs" @tab-click="handleClickTab" :before-leave="handleBeforeTab">
        <el-tab-pane
          v-for="(item,index) in formObject.tabsList"
          :key="index"
          :label="item.displayName" 
          :name="item.attributeName"
        >
          <main-index
            :ref="'formAssembly'+item.attributeName"
            :formData="item"
            :mainSubTable="item.isBase?formObject.mainSubTable:[]"
            :entryObj="{entryFrom: entryFrom,attributeName: item.attributeName,isBase: item.isBase}"
            @handleFormVal="handleFormVal($event,item)"
          >
          </main-index>
        </el-tab-pane>
      </el-tabs>
    </div>
    <div v-else-if="formObject.displayType===2" style="margin-bottom: 10px;">
      <el-collapse v-model="collapse" @change="handleChangeCollapse">
        <el-collapse-item 
          v-for="(item,index) in formObject.tabsList"
          :key="index"
          :title="item.displayName"  
          :name="item.attributeName"
        >
          <main-index
            :ref="'formAssembly'+item.attributeName"
            :formData="item"
            :mainSubTable="item.isBase?formObject.mainSubTable:[]"
            :entryObj="{entryFrom: entryFrom,attributeName: item.attributeName,isBase: item.isBase}"
            @handleFormVal="handleFormVal($event,item)"
          >
          </main-index>          
        </el-collapse-item>
      </el-collapse>
    </div>
    <div v-else-if="formObject.displayType===3">
      <el-steps :active="stepsActive" finish-status="success">
        <el-step
          v-for="(item,index) in formObject.tabsList"
          :key="index"
          :title="item.displayName"
        >
        </el-step>
      </el-steps>
      <div v-for="(item,index) in formObject.tabsList" :key="index">
        <main-index
          class="mt20"
          v-show="stepsActive===index"
          :ref="'formAssembly'+item.attributeName"
          :formData="item"
          :mainSubTable="item.isBase?formObject.mainSubTable:[]"
          :entryObj="{entryFrom: entryFrom,attributeName: item.attributeName,isBase: item.isBase}"
          @handleFormVal="handleFormVal($event,item)"
        >
        </main-index>
      </div>
    </div>
    <!-- footer -->
    <div class="footer" v-if="formObject.displayType!==3">
      <span v-if="entryFrom!='show'">
        <el-button type="primary"  @click="submitFormSave()">确定</el-button>
      </span>
      <el-button @click="handleCancelForm()">取消</el-button>
    </div>
    <div class="footer" v-if="formObject.displayType===3">
      <el-button v-if="this.stepsActive!==0" @click="previousStep">上一步</el-button>
      <el-button v-if="this.stepsActive<this.formObject.tabsList.length-1" @click="nextStep">下一步</el-button>
      <span v-if="entryFrom!='show'">
        <span v-if="this.stepsActive===this.formObject.tabsList.length-1">
          <el-button type="primary"  @click="submitFormSave()">确定</el-button>
        </span>
      </span>
      <el-button @click="handleCancelForm()">取消</el-button>
    </div>
  </div>
</template>
<script>
import MainIndex from './mainIndex'
import specialAttr from '@/utils/special-attr'
export default {
  name: "FormName",
  components: {
    MainIndex
  },
  props: {
    entryFrom: {
      type: String,
      default: null
    },
    // formObject: {
    //   type: Object,
    //   require: true,
    //   default() {
    //     return {
    //       mainSubTable: [],
    //       tabsList: [],
    //       displayType: null
    //     };
    //   },
    // },
    mainSubTable: {
      type: Array,
      default: ()=>[]
    }
  },
  data() {
    return {
      formVal: {},
      formObject: {
        mainSubTable: [],
        tabsList: [],
        displayType: null
      },
      stepsActive: 0,      
      arrayName: ['cascade_select','multi_select','checkbox','tag_select','file','image','transfer'],
      arrayNameImgOrFile: ['file','image'],
      tabs: null,
      collapse: [],
      
    };
  },
  created() {
    
  },
  mounted(){
    
  },
  watch: {
    // 'formData.subTable': {
    //   deep: true,
    //   immediate: true,
    //   handler: function (newValue,oldValue){
    //     if(newValue){
    //       setTimeout(()=>{

    //       },1500)
    //       this.mainSubTable.forEach(item=>{
    //       })
    //     }
    //   }
    // },
    // 'formData': {
    //   deep: true,
    //   immediate: true,
    //   handler: function (newValue,oldValue) {
    //     console.log('formData',this.formData)
        
    //   }
    // },
  },
  methods: {
    handleAsseData(formObj,str){
      this.$set(this.formObject,'displayType',formObj.displayType)
      this.$set(this.formObject,'tabsList',[])
      this.$set(this.formObject,'mainSubTable',[])
      this.tabs = null
      this.collapse = []
      this.stepsActive = 0
      let formObjCopy = JSON.parse(JSON.stringify(formObj))
      if(formObjCopy.elementGroups && formObjCopy.elementGroups.length>0){
        formObjCopy.elementGroups.forEach((item1,index1)=>{
          item1.formList = []
          item1.insertList = []
          if(item1.isSub){
           
            item1.attributeNameNew = item1.attributeName + "List"
           
            formObjCopy[str].elements.forEach((item2,index2)=>{
              if(item1.identifying === item2.groupIdentity){
                item1.insertList.push(item2)
                
              }
            })
            this.formObject.mainSubTable.push(item1)
          }else{
            item1.attributeNameNew = item1.attributeName
            formObjCopy[str].elements.forEach((item2,index2)=>{
              if(item1.identifying === item2.groupIdentity){
                item1.formList.push(item2)
              }
            })
            const obj = {
              labelWidth: formObjCopy[str].labelWidth,
              labelPosition: formObjCopy[str].labelPosition,
              gutter: formObjCopy[str].gutter,
              span: formObjCopy[str].span,
              xs: formObjCopy[str].xs,
              sm: formObjCopy[str].sm,
              md: formObjCopy[str].md,
              lg: formObjCopy[str].lg,
              xl: formObjCopy[str].xl,
              identifying: item1.identifying,    
              billSnowId: item1.billSnowId,    
              entitySnowId: item1.entitySnowId,    
              attributeName: item1.attributeName,    
              attributeNameNew: item1.attributeNameNew,    
              displayName: item1.displayName,    
              className: item1.className,    
              displayOrder: item1.displayOrder,    
              isBase: item1.isBase,    
              isSub: item1.isSub,    
              isSubExtend: item1.isSubExtend,    
              formList: item1.formList 
            }
            this.formObject.tabsList.push(obj)
          }
          
        })
      }
      if(this.formObject.tabsList && this.formObject.tabsList.length>0){
        if(this.formObject.displayType=== 1 || !this.formObject.displayType){
          this.tabs = this.formObject.tabsList[0].attributeName
        }else if(this.formObject.displayType=== 2){
          this.collapse = [this.formObject.tabsList[0].attributeName]
        }else if(this.formObject.displayType=== 3){
          this.stepsActive = 0
        }
        
      }
      this.$nextTick(()=>{
        if(this.formObject.tabsList && this.formObject.tabsList.length>0){
          this.formObject.tabsList.forEach((item,index)=>{
            if(item.isBase){
              item.subTable = JSON.parse(JSON.stringify(formObjCopy.subTable))
            }
            this.$refs['formAssembly'+item.attributeName][0].handleInit()
          })
        }
      })
      console.log('formObject',this.formObject)
    },
    // tab页切换
    handleClickTab(){
      
    },
    // tab离开之前的钩子函数
    handleBeforeTab(val,oldVal){
      if(this.$refs['formAssembly'+oldVal] && this.$refs['formAssembly'+val]){
        if(!this.$refs['formAssembly'+oldVal][0].handleBeforeTabs()){
          this.$message({
            type: 'warning',
            message: '请先填写当前表单的必填项!'
          })
          return false
        }
      }
      

    },
    // 保存
    submitFormSave(){
      if(this.formObject.tabsList && this.formObject.tabsList.length>0){
        let i;
        let flag = true
        for(i=0;i<this.formObject.tabsList.length;i++){
          if(!this.$refs['formAssembly'+this.formObject.tabsList[i].attributeName][0].handleBeforeTabs()){
            flag = false
          }
        }
        if(flag){
          const formValCopy = JSON.parse(JSON.stringify(this.formVal));
          //主子表中需要把arrayName中的数组转字符串
          if(this.formObject.mainSubTable && this.formObject.mainSubTable.length>0){
            this.formObject.mainSubTable.forEach((item,index)=>{
              item.insertList.forEach((item1,index1)=>{
                if(this.arrayName.includes(item1.editType)){
                  this.formVal['base'][item.attributeNameNew].forEach((item3,index3)=>{
                    if(item1.fieldSpecialType != specialAttr.fieldSpecialType.MTM_TYPE.code){
                      if(this.arrayNameImgOrFile.includes(item1.editType)){
                        formValCopy['base'][item.attributeNameNew][index3][item1.prop] = [];
                        if(this.formVal['base'][item.attributeNameNew][index3][item1.prop]){
                          this.formVal['base'][item.attributeNameNew][index3][item1.prop].forEach(item4=>{
                            // formValCopy['base'][item.attributeNameNew][index3][item1.prop].push(item4.response.data.path)
                            formValCopy['base'][item.attributeNameNew][index3][item1.prop].push(JSON.stringify({
                              name: item4.name,
                              path: item4.response?item4.response.data.path:item4.path
                            }))
                          })
                        }
                        formValCopy['base'][item.attributeNameNew][index3][item1.prop] = this.getArrayToStrByCommaImage(formValCopy['base'][item.attributeNameNew][index3][item1.prop])
                      }else{
                        formValCopy['base'][item.attributeNameNew][index3][item1.prop] = this.getArrayToStrByComma(this.formVal['base'][item.attributeNameNew][index3][item1.prop])
                      }
                      // formValCopy['base'][item.attributeNameNew][index3][item1.prop] = this.getArrayToStrByComma(this.formVal['base'][item.attributeNameNew][index3][item1.prop])
                    }
                  })
                }
              })
            })
          }
          // form表单中（非主子表）需要把arrayName中的数组转字符串
          if(this.formObject.tabsList && this.formObject.tabsList.length>0){
            this.formObject.tabsList.forEach((item,index)=>{
              item.formList.forEach((item1,index1)=>{
                if(this.arrayName.includes(item1.editType)){
                  if(item1.fieldSpecialType != specialAttr.fieldSpecialType.MTM_TYPE.code){
                    if(this.arrayNameImgOrFile.includes(item1.editType)){
                      formValCopy[item.isBase?'base':item.attributeName][item1.prop] = [];
                      if(this.formVal[item.isBase?'base':item.attributeName][item1.prop]){
                        this.formVal[item.isBase?'base':item.attributeName][item1.prop].forEach(item2=>{
                          // formValCopy[item.prop].push(item1.response.data.path)
                          formValCopy[item.isBase?'base':item.attributeName][item1.prop].push(JSON.stringify({
                            name: item2.name,
                            path: item2.response?item2.response.data.path:item2.path
                          }))
                        })
                      }
                      formValCopy[item.isBase?'base':item.attributeName][item1.prop] = this.getArrayToStrByCommaImage(formValCopy[item.isBase?'base':item.attributeName][item1.prop])
                    }else{
                      formValCopy[item.isBase?'base':item.attributeName][item1.prop] = this.getArrayToStrByComma(this.formVal[item.isBase?'base':item.attributeName][item1.prop])
                    }
                  }
                }
              })
            })
          }
          Object.assign(formValCopy,formValCopy.base)
          delete formValCopy.base
          let obj = {}
          if(this.formObject.tabsList && this.formObject.tabsList.length>0){
            this.formObject.tabsList.forEach((item,index)=>{
              if(item.isBase){
                item.formList.forEach((item1,index1)=>{
                  if(item1.isExtend){
                    console.log('item',item)
                    obj[item1.prop] = formValCopy[item1.prop]
                    delete formValCopy[item1.prop]
                  }
                })
              }
            })
          }
          formValCopy.extension = JSON.stringify(obj)
          this.$emit('makeSure',formValCopy)

        }else{
          this.$message({
            type: 'warning',
            message: '此表单有未保存的必填项，请仔细检查填写必填项后再进行保存!'
          })
        }
      }
    },
    // 让表单校验置空
    handleCancelForm(){
      this.tabs = null
      this.collapse = []
      this.stepsActive = 0
      if(this.formObject.tabsList && this.formObject.tabsList.length>0){
        this.formObject.tabsList.forEach((item,index)=>{
          this.$refs['formAssembly'+item.attributeName][0].cancelForm()
        })
      }
      this.$emit('cancel')
    },

    // 折叠面板改变
    handleChangeCollapse(val){

    },
    // 步骤条上一步
    previousStep(){
      if(this.$refs['formAssembly'+this.formObject.tabsList[this.stepsActive].attributeName][0].handleBeforeTabs()){
        if(this.stepsActive>0){
          this.stepsActive --
        }        
      }else{
        this.$message({
          type: 'warning',
          message: '请先填写当前表单的必填项!'
        })
      }
    },
    // 步骤条下一步
    nextStep(){
      if(this.$refs['formAssembly'+this.formObject.tabsList[this.stepsActive].attributeName][0].handleBeforeTabs()){
        if(this.stepsActive<this.formObject.tabsList.length){
          this.stepsActive ++
        }        
      }else{
        this.$message({
          type: 'warning',
          message: '请先填写当前表单的必填项!'
        })
      }
      
    },
    // 单个form表单变动的时候给大form表单赋值
    handleFormVal(e,row){
      if(row.isBase){
        this.$set(this.formVal,'base',e)

      }else{
        this.$set(this.formVal,row.attributeName,e)
      }
    },
    //array转为元素以 ';' 分隔的字符串
    getArrayToStrByCommaImage(ary) {
      if(ary != null && ary != undefined){
        let str = ''
        str = ary.join(';')
        return str
      }
    },
    //array转为元素以 ',' 分隔的字符串
    getArrayToStrByComma(ary) {
      if(ary != null && ary != undefined){
        let str = ''
        str = ary.join(',')
        return str
      }
    },

  },
};
</script>
<style lang="scss" scoped>
.formBox {
  .mt20{
    margin-top: 20px;
  }
  .footer{
    text-align: center;
    padding: 10px 0 20px;
  }
  
}
</style>


